<template>
    <div id="loveBox" class="love" ref="viewBox">
        <div class="search_fiexd">
            <div class="serchImg" v-show="searchImgShow" @click="serchClick">
                <img src="../../assets/search.png">
            </div>
            <yd-slider autoplay="3000">
                <yd-slider-item v-for="(item,index) in bannerList" :key="index">
                    <a :href="item.advUrl">
                        <img style="min-height:3.8rem" :src="imgUrl+item.advContent">
                    </a>
                </yd-slider-item>
            </yd-slider>      
        </div>
        <!--扶贫县  -->
        <div id="countyListPanel" class="m-grids-5">
            <!-- <div class="grids-item" v-for="(item,index) in countyList" :key='index' @click="jumpTo(index)"> -->
            <div class="grids-item" v-for="(item,index) in countyList" :key='index' @click="toCounty(item.countyId, 0)">
                <div class="grids-icon"><img :src="imgUrl+item.countyIcon"></div>
                <div class="grids-txt"><span>{{item.countyName}}</span></div>
            </div>
        </div>
        <!--商品  -->
        <div id="goodsListPanel">
            <ul class="goods_ul" v-for="(countyItem, key) in countyList" :key="key">
                <li class="countypanel" style="height:40px;border-top:2px solid #d9d9d9;border-bottom:none">
                    <!-- <div class="county_lefts" @click='toCounty(countyItem.countyId, 0)'>{{countyItem.countyArea | formatArea}}</div> -->
                    <div class="county_lefts">{{countyItem.countyArea | formatArea}}</div>
                    <!--多个干部  -->
                    <!-- <div class="county_rights" v-if="countyItem.cadreList.length > 0">
                        <img slot="icon" style="width:38px;height:38px;padding-left:3px" v-for="(cadreItem, indexs) in countyItem.cadreList" :key="indexs" :src="imgUrl+cadreItem.cadreAvatar"  @click='toCadre(cadreItem.cadreId, countyItem.countyId)'>
                    </div> -->
                </li>
                <li v-if="countyItem.goodsCommonList.length > 0">
                    <!-- <div style="height:auto"> -->
                        <yd-list theme="3" slot="list">
                            <!-- <yd-list-item :href="{name: 'commodity',query: {goodsCommonid: goodItem.goodsCommonid}}" type="link" v-for="(goodItem, indexs) in countyItem.goodsCommonList" :key="indexs"> -->
                            <yd-list-item v-for="(goodItem, indexs) in countyItem.goodsCommonList" :key="indexs">
                                <img slot="img" style="height:3.35rem;" :src="imgUrl+goodItem.goodsImage" @click="commodity(goodItem.goodsCommonid)">
                                <span slot="title">{{goodItem.goodsName}}</span>
                                <yd-list-other slot="other">
                                    <div>
                                        <span class="demo-list-price">
                                            <em>¥</em>
                                            <yd-countup :endnum="goodItem.goodsPrice" duration="0.1" decimals="2" separator=","></yd-countup>
                                        </span>
                                    </div>
                                </yd-list-other>
                            </yd-list-item>
                        </yd-list>
                    <!-- </div> -->
                </li>
                <!-- <li v-else style="border-top:0.5px solid #d9d9d9;border-bottom:none">
                    <div style="padding-left:0.2rem;color:#FB6C68;">该县暂无扶贫商品</div>
                </li> -->
            </ul>
        </div>
        <!-- <yd-backtop></yd-backtop> -->
        <div class="backtop" v-show="backTopImgShow" @click="backTop">
            <img src="../../assets/toTop.png">
        </div>
        <!--购物车  -->
        <div class="shopping" @click="shoppingCart">
            <yd-icon name="shopcart-outline" size='0.5rem'></yd-icon>
            <yd-badge class="badge" type="danger" v-if="shoppingNum>0">{{shoppingNum}}</yd-badge>
        </div>
    </div>    
</template>

<script>

export default {
    name: 'love',
    data() {
        return {
            imgUrl: this.CONSTANT.imgBaseUrl,
            bannerList: [],
            countyList: [],
            searchLove: '',
            shoppingNum: 0,
            searchImgShow: true,
            backTopImgShow: false,
            beforeRouteName: '',
        }
    },
    beforeRouteEnter (to, from, next) {
        // 导航转入新的路由前获取数据,this不可用
        // this.beforeRouteName = from.name;
       next(vm => {
            vm.beforeRouteName = from.name;
        });
    },
    filters: {
        formatArea(countyArea) {
            // 用空格分隔，只取第一个和最后一个
            let area = countyArea.split(' ');
            return area[0]+area[area.length-1];
        }
    },
    created: function() {
        // 当前页面是从易连互动返回的场合
        if (this.$store.state.pageToPage == 'meToLottery') {
            this.$store.commit('pageToPage', '');
            this.$router.push('/me');
        }
        this.$dialog.loading.open('请稍后');
        this.init(5);
    },
    mounted: function() {
        this.$store.commit('routerTo', '/');
        // this.$nextTick(() => {
        //     let loves = document.getElementById('countyListPanel');
        //     let loveBox = document.getElementById('loveBox');
        //     let tops = document.getElementById('countyListPanel').offsetTop;
        //     document.getElementById('scrollView').onscroll = function(e) {
        //         let top = e.target.scrollTop;
        //         // if (top >= tops) {
        //         //     loves.classList.add("loveFixd");
        //         //     loveBox.style.paddingTop = '1.2rem';
        //         // } else {
        //         //     loves.classList.remove("loveFixd");
        //         //     loveBox.style.paddingTop = '0';
        //         // }
        //         window.alert(top);
        //         if (top > 180) {
        //            this.searchImgShow = false;
        //         }
        //     }
        // })

        // 通过$refs获取dom元素
        let box = this.$refs.viewBox
        // 监听这个dom的scroll事件
        box.addEventListener('scroll', () => {
            //console.log(" scroll " + this.$refs.viewBox.scrollTop)
            //以下是我自己的需求，向下滚动的时候显示“我是有底线的（类似支付宝）”
            // this.isScroll=this.$refs.viewBox.scrollTop>0
            if (this.$refs.viewBox.scrollTop > 150) {
                this.searchImgShow = false;
                this.backTopImgShow = true;
            } else {
                this.searchImgShow = true;
                this.backTopImgShow = false;
            }
        }, false);
    },
    methods: {
        init(item) {
            this.$axios.get(this.CONSTANT.wapiBaseUrl + 'adv/list?apId=' + item)
                .then((response) => {
                    if (response.status == 200) {
                        for (var i = 0; i < response.data.object.length; i++) {
                            var advUrl = response.data.object[i].advUrl;
                            if (advUrl == '') {
                                response.data.object[i].advUrl = 'javascript:;'
                            }
                        }
                        this.bannerList = response.data.object;
                    }

                    // 扶贫县，扶贫县商品的取得
                   this.contyInfo();
                })
                .catch(error => {
                    this.$dialog.loading.close();
                    this.$dialog.toast({
                        mes: '广告信息的取得失败，请联系客服',
                        icon: 'error',
                        timeout: 1500
                    });
                });
        },
        contyInfo() {
            this.$axios.get(this.CONSTANT.wapiBaseUrl + 'supportPoor/countyList?recommendType=axzl')
                .then((response) => {
                    if (response.status == 200) { 
                        // 扶贫县LIST、以及对应的商品LIST
                        this.countyList = response.data.object;
                    }
                    
                    // 购物车件数的取得
                    this.nums();
                })
                .catch(error => {
                    this.$dialog.loading.close();
                    this.$dialog.toast({
                        mes: '贫困县信息的取得失败，请联系客服',
                        icon: 'error',
                        timeout: 1500
                    });
                });
        },
        nums() {
            this.$axios.get(this.CONSTANT.wapiBaseUrl + 'member/statistics')
                .then((response) => {
                    this.$dialog.loading.close();
                    if (response.status == 200) {
                        this.shoppingNum = response.data.object.cartGoodsNum;
                    }

                    // 所有数据都正常检索完后再设置(必选是当前页面，页面未加载完就跳转的话不再设置scrollTop)
                    if (this.$refs.viewBox != undefined) {
                        // 从跳转后的页面返回时（购物车需要先去login页面）
                        if (this.beforeRouteName == 'commodity' || 
                                this.beforeRouteName == 'countyInfo' || this.beforeRouteName == 'cadreInfo' || 
                                this.beforeRouteName == 'shoppingCart' || this.beforeRouteName == 'fastLogin') {

                            // 设置当前页面滚动条的位置
                            let scrollPostion = this.$store.state.scrollPostion || 0;
                            if (scrollPostion > this.$refs.viewBox.scrollHeight) {
                                this.$refs.viewBox.scrollTop = 0;
                            } else {
                                this.$refs.viewBox.scrollTop = scrollPostion;
                            }
                        } else {
                            // 从前页面正常跳转时
                            this.$refs.viewBox.scrollTop = 0;
                        }
                    }
                })
                .catch(error => {
                    this.$dialog.loading.close();
                    this.$dialog.toast({
                        mes: '购物车信息的取得失败，请联系客服',
                        icon: 'error',
                        timeout: 1500
                    });
                });
        },
        serchClick() {
            // this.$router.push('/lovefpzq');
            this.$store.state.searchLove = '';
            this.$router.push('/lovelist');
        },
        jumpTo(index) {
            // offsetTop则是元素的上边框与父元素的上边框的绝对距离
            // scrollTop是指某个可滚动区块向下滚动的距离           
            //this.$refs.viewBox.scrollTop = document.querySelectorAll('.countypanel')[index].offsetTop;
            let total = document.querySelectorAll('.countypanel')[index].offsetTop;
            //动画效果的话，需要 smoothDown、smoothUp,设置需要滑动的时间和每次滑动的距离等
            let distance = this.$refs.viewBox.scrollTop;
            // 平滑滚动，时常500ms、每15ms一跳、共50跳
            let step = total / 50;

           this.smoothDown(distance, total, step);
           //this.$refs.viewBox.animate({scrollTop: total}, 1500);
        },
        smoothDown(distance, total, step) {
            if (distance < total) {
                distance = distance + step;
                this.$refs.viewBox.scrollTop = distance;
                //setTimeout(smoothDown, 10);                
                setTimeout(() => {
                    this.smoothDown(distance, total, step);
                }, 15);
            } else {
                this.$refs.viewBox.scrollTop = total;
            }
        },
        smoothUp(distance, total, step) {
            if (distance > total) {
                distance = distance - step;
                this.$refs.viewBox.scrollTop = distance;
                //setTimeout(smoothDown, 10);                
                setTimeout(() => {
                    this.smoothUp(distance, total, step);
                }, 15);
            } else {
                this.$refs.viewBox.scrollTop = total;
            }
        },
        commodity(goodsCommonid) {
            // 保存当前滚动条的位置
            this.$store.commit('scrollPostion', this.$refs.viewBox.scrollTop);
            this.$router.push({
                name: 'commodity', 
                query: { 
                    goodsCommonid: goodsCommonid 
                }
            });
        },
        toCounty(countyId, tabIndex) {
            // 保存当前滚动条的位置
            this.$store.commit('scrollPostion', this.$refs.viewBox.scrollTop);
            this.$router.push({
                name: 'countyInfo',
                query: {
                    countyId: countyId
                }
            });
        },
        toCadre(cadreId, countyId) {
            // 保存当前滚动条的位置
            this.$store.commit('scrollPostion', this.$refs.viewBox.scrollTop);
            this.$router.push({
                name: 'cadreInfo',
                query: {
                    cadreId: cadreId,
                    countyId: countyId
                }
            });
        },
        backTop() {
            //this.$refs.viewBox.scrollTop = 0;
            let distance = this.$refs.viewBox.scrollTop;            
            let total = 0;
            // 平滑滚动，时常500ms、每15ms一跳、共50跳
            let step = distance / 50;

            this.smoothUp(distance, total, step);
        },
        shoppingCart() {
            // 保存当前滚动条的位置
            this.$store.commit('scrollPostion', this.$refs.viewBox.scrollTop);
            this.$router.push('/shoppingCart');
        }
    }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.love {
    width: 100%;
    /* height: auto;
    overflow: hidden; */
    height: 10.8rem;
    /* overflow: auto; */
    overflow-y: scroll;
}

 /*广告图片 检索图片*/
.serchImg {
    position: absolute;
    right: 0.2rem;
    top: 0.2rem;
    width: 0.7rem;
    height: 0.7rem;
    z-index: 99;
}
.serchImg img {
    width: 100%;
    height: 100%;
    display: block;
}

/*九个扶贫县的显示*/ 
.m-grids-5 {
  overflow: hidden;
  position: relative;
  background-color: #FFF;
}
.m-grids-5:before {
  content: '';
  position: absolute;
  z-index: 1;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 1px;
  /* border-bottom: 1px solid #B2B2B2; */
  -webkit-transform: scaleY(0.5);
  transform: scaleY(0.5);
  -webkit-transform-origin: 0 100%;
  transform-origin: 0 100%;
  border-bottom:none;
}
.grids-item {
  width: 20%;
  float: left;
  position: relative;
  z-index: 0;
  padding: 0.15rem 0;
  font-size: 0.28rem;
}
.m-grids-5 .grids-item:not(:nth-child(5n)):before {
  content: '';
  position: absolute;
  z-index: 0;
  top: 0;
  right: 0;
  height: 90%;
  /* border-right: 1px solid #D9D9D9; */
  -webkit-transform: scaleX(0.5);
  transform: scaleX(0.5);
  -webkit-transform-origin: 100% 0;
  transform-origin: 100% 0;
  border-right:none;
}
.grids-item:after {
  content: '';
  position: absolute;
  z-index: 0;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 1px;
  /* border-bottom: 1px solid #D9D9D9; */
  -webkit-transform: scaleY(0.5);
  transform: scaleY(0.5);
  -webkit-transform-origin: 0 100%;
  transform-origin: 0 100%;
  border-bottom:none;
}
.grids-icon {
  height: .68rem;
  display: -webkit-box;
  display: -webkit-flex;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-pack: center;
  -webkit-justify-content: center;
  -ms-flex-pack: center;
  justify-content: center;
  -webkit-box-align: center;
  -webkit-align-items: center;
  -ms-flex-align: center;
  align-items: center;
}
.grids-icon img {
  height: 100%;
}
.grids-txt {
  word-wrap: normal;
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
  text-align: center;
  color: #333;
  padding: 0 .2rem;
}

/*扶贫县及其商品信息*/
.goods_ul {
    width: 100%;
    height: auto;
    /* padding: 0.15rem 0.1rem; */
    padding-left: 0.1rem;
    padding-right: 0.1rem;
    font-size: 14px;
    box-sizing: border-box;
}
.goods_ul li {
    width: 100%;
    /* height: 0.7rem; */
    /* line-height: 0.7rem; */
    overflow: hidden;
}
.county_lefts {
    width: 50%;
    height: 100%;
    float: left;
    padding-top:15px;
}
.county_rights {
    width: 50%;
    height: 100%;
    float: right;
    padding-right: 2px;
    /* color: #FB6C68; */
    text-align: right;
}

/*商品信息*/
.love .yd-list-title {
    height: auto;
    overflow: hidden;
    line-height: 0.4rem;
    font-size: 14px;
}
.love .demo-list-price {
    font-size: 14px;
    color: #c7000a;
}

.decoration-price {
    margin-left:12px;
    font-size:10px;
    color:#666;
    text-decoration:line-through;
}

/*返回顶部*/
.backtop {
    position: fixed;
    right: 5%;
    bottom: 10.6rem;
    /* bottom: 1.2rem; */
    width: 1rem;
    z-index: 99;
    text-align: center;
    line-height: 1rem;
    color: #fff;
    font-weight: 400;
    height: 1rem;
    border-radius: 50%;
    /* background: #F4A9A3; */
}
.backtop img{
    width:47px;
    height:47px;
}

/*购物车*/
.shopping {
    position: fixed;
    right: 5%;
    bottom: 1.2rem;
    width: 1rem;
    z-index: 99;
    text-align: center;
    line-height: 1rem;
    color: #fff;
    font-weight: 400;
    height: 1rem;
    border-radius: 50%;
    background: #F4A9A3;
}
.badge {
    position: absolute;
    right: 0;
    top: -0.1rem;
}
</style>